//
//  author: Paul Cheffers paul@securecottage.com
//  Securecottage
//  this code is open source
//
// this code is a gadget on en.wikipedia.org
// and several other wikipedias.

// GoogleTrans -- Translation Popups
// does google toolbar like translation of words and selected text
// works on ie and firefox, epiphany, safari, and Opera but still has bugs on Konqueror
// Use:
//
//  1) position cursor over word in webpage
//  2) hold down SHIFT key
//  result: popup appears with translation of 
//  word under cursor.

//
//  OR
//  1) select text (less than 500 characters)
//  2) position cursor within selected text
//  3) hold down SHIFT key
//  result: popup appears with translation of
//  selected text

// In IE, you can do the hover effect for
// textareas and input fields too.  
// (Programmers: figure out how to trap the
// mousemove event when in textareas and input fields
// and it can be turned on for firefox as well)
// In this case a "Replace Text?"  link apears
// in the popup.  You can replace text in 
// input fields this way with foreign language 
// translations.



// Wikipedia Lookup
// you can get a wikipedia article on any term
// within the website by

// 1) position cursor over first word in webpage
// 2) hold down SHIFT key
// 3) click on 'Wikipedia?' link in popup
// 4) a menu of cascading terms appears in popup
// 5) click on link in popup that is a sensible
//    wikipedia request
// 6) Wikipedia article popups in another window or tab
//
// The dictionarylookup and Wikipedialookup alternate.  If you do a Wikipedialookup, the next
// time you position cursor and hold shift key down
// the wikipedia menu pops up instead of the 
// dictionarylookup popup (click on 'Dictionary?' link
// to return to dictionarylookup)
//




//
// currently runs in two modes
//
// 1) proxy mode where the dictafy20.cgi perl script
// reads a webpage, converts all links in that webpage to dictafy20.cgi links with a data item holding the original URL
// dictafy20.cgi presents the foreign website to
// the user and injects dictionarylookup20.js along
// with some other stuff into the webstuff.
//
// you can surf the web this way and inject dictionarylookup/wikipedialookup behavior into most
// webpages.

// 2) standalone mode.  runs as part of the webpage
// because you have done the following in your html/javascript code
//
// Place in your navigation bar code etc
//
//<a href="javascript:SCdoTranslationPopups()"
// id="SCTranslationPopups">Translation Popups</a>
//<script
// src="http://www.securecottage.com/dictionarylookup20.js">
// </script>
//
// change the securecottage.com stuff to your domain name
// and have the client turn on the behavior by clicking on the link

//
// dictionarylookup20.js (10k) dynamically invokes 
// dictionarylookup20a.js (80k) if the 
// GoogleTrans option is turned on
//

// You need to fill in certain default strings
// at the top of dictionarylookup20.js 
// and dictafy20.cgi (if using proxy option)
// if you are hosting this code


var SCweblookup = "";
// var SCweblookup = "Wikipedia"; // if Wikipedialookups to be the default action!
var SCGoogleTrans=false;
var SCSettingsUponStartup = false;
var SCstrTranslationPopups = "GoogleTrans -";
var SCstrOn = "ON";
var SCstrOff = "OFF";
var SCstrLoading = "LOADING";

if(typeof SCbIsProxy == "undefined")
  SCbIsProxy = false;
if(typeof SCbIsProxy1 == "undefined")
  SCbIsProxy1 = false;
var SCProxyUrl = "http://www.securecottage.com";
var SCtheURL = "http://www.securecottage.com";
var SCtheself = "dictionarylookup20a.js";
var SCProxySelf = "/cgi-bin/dictafy20.cgi";
if(typeof SCpath != "undefined")
{
  //  SCProxySelf = SCpath;
}
var SCreframe="http:\\/\\/www\\.securecottage\\.com\\/iframe\\.html";
var SCstrframe = 
    "http://www.securecottage.com/iframe.html";

  var SCre1 = new RegExp("^/?cgi-bin/dictafy20.cgi","i");
  var SCre2 = new RegExp("\.(gif|jpg|jpeg|swf|png|tiff)$","i");
  var SCre3 = new RegExp("^https?://www.securecottage.com/cgi-bin/(.*)$","i");
  var SCre4 = new RegExp("translate\.google\.com","i");



var SCbIsIE=false;
var SCbIsIE8=false;
if(navigator.appVersion.match(/MSIE/i))
{
  SCbIsIE = true;
  if(navigator.userAgent.indexOf('MSIE 8') != -1)
     SCbIsIE8 = true;
  
}



function SCappendCSS(text) {
        var s = document.createElement('style');
        s.type = 'text/css';
        s.rel = 'stylesheet';
        if (s.styleSheet) s.styleSheet.cssText = text //IE
        else s.appendChild(document.createTextNode(text + '')) //Safari sometimes borks on null
        document.getElementsByTagName('head')[0].appendChild(s);
        return s;
}


SCappendCSS(
'.highlight {border:1px solid ' + 'black;background-color:pink; ' +
'             padding:4px;} ' 
);

SCappendCSS(
 '.gBrandingText {background : white;   }'
);


var SCloadedScripts = {}; // included-scripts tracker
function SCimportScriptURI(url) {
        if (SCloadedScripts[url]) {
           //     return null;
        }
        SCloadedScripts[url] = true;
        var s = document.createElement('script');
        s.setAttribute('src',url);
        s.setAttribute('type','text/javascript');
        document.getElementsByTagName('head')[0].appendChild(s);
        return s;
}

function SChookEvent(hookName, hookFunct) {
        if (window.addEventListener) {
                window.addEventListener(hookName, hookFunct, false);
        } else if (window.attachEvent) {
                window.attachEvent("on" + hookName, hookFunct);
        }
}


 

function SCImportScripts()
{
 var hl = "";
  
  SCimportScriptURI(SCtheURL + "/" + SCtheself);
//  SCimportScriptURI("http://www.securecottage.com/dictionarylookup20a.js");

}
 function SCCreateSCitem()
{
 var span1 = document.createElement('DIV');
        span1.setAttribute('id','SCitem');
        span1.onMouseover=new Function("return SCdonthide=true;");
        
        var thebody = document.getElementsByTagName('BODY');
        thebody[0].appendChild(span1);
}
 function SConloadscitem() {
        /*
        var span1 = document.createElement('DIV');
        span1.setAttribute('id','SCitem');
        span1.onMouseover=new Function("return SCdonthide=true;");
        
        var thebody = document.getElementsByTagName('BODY');
        thebody[0].appendChild(span1);
        */

    // var span2 = document.createElement('SPAN');
    //    span2.setAttribute('id','SCPersistElement');
    //    span2.setAttribute('class','SCuserData');
    //    span2.className="SCuserData";
    //      span2.style.behavior = "url('#default#userData')";
     //   thebody[0].appendChild(span2);
      

      SCImportScripts();

     if(typeof SCbDictionarylookup12Loaded != "undefined" &&
        SCbDictionarylookup12Loaded)
      {
        SCTextSettings();
        SCsetLanguages();
      }
     else setTimeout("SCTimeoutsetLanguages()",1000);

}

function SCTimeoutsetLanguages()
{
    
    if(typeof SCbDictionarylookup12Loaded != "undefined" &&
        SCbDictionarylookup12Loaded)
    {
        SCTextSettings();
        SCsetLanguages();
    }
    else setTimeout("SCTimeoutsetLanguages()",1000);
}

function SCaddOnloadHook(func)
{
  SChookEvent("load",func);
}

// for proxy use
//  ie - use cookies
//  firefox - use globalstorage

// for direct javascript use
// use cookies

function SCPersistantSave(key,value)
{
  try {
  if(SCbIsProxy||SCbIsProxy1)
  {
   if(SCbIsIE && 1==0)
       SCUserDataSave(key,value);
   else if(typeof globalStorage != "undefined") 
       SCGlobalStorageSave(key,value);
   else 
   SCsetcookieVal(key,value);
   }
   else SCsetcookieVal(key,value);
  }
  catch(err) {
//alert("scpersistantsave"); 
}
}
function SCPersistantLoad(key)
{
   var retValue="";
   try {
   if(SCbIsProxy||SCbIsProxy1)
   {
        if(SCbIsIE && 1==0)
        return SCUserDataLoad(key);
        else if(typeof globalStorage != "undefined") 
        return SCGlobalStorageLoad(key);
        else 
                retValue = SCgetcookieVal(key);
   }
   else retValue = SCgetcookieVal(key);
   }
   catch(err) { retValue = ""; 
//alert("scpersistantsave");
              }

   return retValue;
 
}

function SCUserDataSave(key,value)
{
  
  var obj = document.getElementById("SCPersistElement");
  if(!obj)
  {
    alert("no scpersistElement");
    return;
  }
  obj.setAttribute(key,value);
  obj.save("oXMLStore");
  

}
function SCUserDataLoad(key)
{
  
  var obj = document.getElementById("SCPersistElement");
  if(!obj)
  {
    alert("no scpersistElement");
    return;
  }


  obj.load("oXMLStore");
  var retc = obj.getAttribute(key);
  if(retc == null)
    retc = "";
  

  return retc;
}
function SCGlobalStorageSave(key,value)
{
  var SCProxyUrl1 = SCProxyUrl;
  if(SCProxyUrl.match(/^https?:\/\/(.*)$/))
    SCProxyUrl1 = RegExp.$1;
  if(globalStorage)
  {
    eval ("globalStorage['" +SCProxyUrl1+ "']." +
          key + "='" + value + "'");
  }
}
function SCGlobalStorageLoad(key)
{
  var retc = "";
  if(globalStorage)
  {
  var SCProxyUrl1 = SCProxyUrl;
  if(SCProxyUrl.match(/^https?:\/\/(.*)$/))
    SCProxyUrl1 = RegExp.$1;

     retc =     eval ("globalStorage['" + SCProxyUrl1+"']." +
          key );
     if (retc == null)
        return "";
     
     return retc.value;
     
  }
  return "";
}

function SCsetcookieVal(cookieKey,cookieValue)
{
   var ExpireDate = new Date();
   var days=180;
   var ifsecure = "";

   if(document.location.href.match(/^https/i))
   {
      ifsecure = " secure; ";
   }
//   ExpireDate.setTime(ExpireDate.getTime()+(days*24*60*60*1000));
ExpireDate.setYear(ExpireDate.getUTCFullYear()+1);

   document.cookie =  cookieKey + '=' + cookieValue + 
          "; path=/; " +
          
          "; expires=" + ExpireDate.toGMTString() + ifsecure;
}

function SCgetcookieVal(cookieName)
{
  
  var aCookie = "";
  var thisCookie;

  
  
  aCookie = document.cookie;
  thisCookie = aCookie.split("; ");

  var i;
  var retCookie = "";
  for(i=0;i<thisCookie.length;i++)
  {
     if(cookieName == thisCookie[i].split("=")[0].substring(0,cookieName.length))
     {
           retCookie = thisCookie[i].split("=")[1];
           break;
     }
  }
  
  return retCookie;

}



/*
if(SCbIsProxy)
   SCGoogleTrans = true;
else if(SCPersistantLoad('GoogleTrans') == '1')
   SCGoogleTrans = true;


if(SCGoogleTrans)
   SConloadscitem();
*/

function SCdoTranslationPopups()
{
   var bIsOn = SCPersistantLoad('GoogleTrans');
   if(typeof SCbDictionarylookup12Loaded == "undefined"
      && (bIsOn == "0" || bIsOn == ""))
   {
      SCSettingsUponStartup = true;
      SCGoogleTrans = true;
      SConloadscitem();
      SCTextSettings();
     
   }
   else if(typeof SCbDictionarylookup12Loaded != "undefined")
   {
     SCSettings();
     SCTextSettings();
   }
   
  // SCTextSettings();
}
function SCTextSettings()
{
  
  
  SCPersistantSave('GoogleTrans',(SCGoogleTrans)?"1":"0");
  var popsid = document.getElementById("SCTranslationPopups");
  if(!popsid)
  {
      setTimeout("SCTextSettings()",1000);
      return;
  }
  var anchor1 = popsid;

  if(!popsid.nodeName.match(/^a$/i))
    anchor1 = popsid.getElementsByTagName( "a" )[0];
  if(!anchor1)
     return;

  var text1; 
  
  if(SCGoogleTrans && 
     typeof SCbDictionarylookup12Loaded == "undefined")
  {
   text1 = document.createTextNode(SCstrTranslationPopups + SCstrLoading);
  }
 
  else 
  if(SCGoogleTrans &&
     typeof SCbDictionarylookup12Loaded != "undefined")
    text1 = document.createTextNode(SCstrTranslationPopups + SCstrOn);
  else 
    text1 = document.createTextNode(SCstrTranslationPopups + SCstrOff);
  

 // delete text from anchor in tab
 while(anchor1.childNodes.length>0)
 {
   anchor1.removeChild(anchor1.childNodes[0]);
 }
 // replace text in anchor in tab
 anchor1.appendChild(text1);
   
if(typeof SCbGoogleLanguageLoaded != "undefined" &&
   SCbGoogleLanguageLoaded)
{

//google.language.getBranding('SCTranslationPopups');
}

}



if(SCbIsProxy||SCbIsProxy1)
{
   SCGoogleTrans = true;
   SCPersistantSave('GoogleTrans','1');
}
else if(SCPersistantLoad('GoogleTrans') == '1')
   SCGoogleTrans = true;

SCCreateSCitem();
if(SCGoogleTrans)
{
   //SChookEvent("load",SConloadscitem);
   SConloadscitem();
 //  SCTextSettings();
}
// 90 percent of Google requests are for the language list
// better to hardcode it in this case
// list made 8/10/2011
// may have to remake list if Indian regional languages become supported.
var SCGoogleLanguageNames = [
'Afrikaans',
'Albanian',
'Arabic',
'Belarusian',
'Bulgarian',
'Catalan',
'Chinese (traditional)',
'Chinese (simplified)',
'Croatian',
'Czech',
'Danish',
'Dutch',
'English',
'Estonian',
'Filipino',
'Finnish',
'French',
'Galician',
'German',
'Greek',
'Haitian creole',
'Hebrew',
'Hindi',
'Hungarian',
'Icelandic',
'Indonesian',
'Irish',
'Italian',
'Japanese',
'Latvian',
'Lithuanian',
'Macedonian',
'Malay',
'Maltese',
'Norwegian',
'Persian',
'Polish',
'Portuguese',
'Romanian',
'Russian',
'Serbian',
'Slovak',
'Slovenian',
'Spanish',
'Swahili',
'Swedish',
'Thai',
'Turkish',
'Ukrainian',
'Vietnamese',
'Welsh',
'Yiddish'];
var SCGoogleLanguageCodes = [
'af',
'sq',
'ar',
'be',
'bg',
'ca',
'zh-TW',
'zh-CN',
'hr',
'cs',
'da',
'nl',
'en',
'et',
'tl',
'fi',
'fr',
'gl',
'de',
'el',
'ht',
'iw',
'hi',
'hu',
'is',
'id',
'ga',
'it',
'ja',
'lv',
'lt',
'mk',
'ms',
'mt',
'no',
'fa',
'pl',
'pt',
'ro',
'ru',
'sr',
'sk',
'sl',
'es',
'sw',
'sv',
'th',
'tr',
'uk',
'vi',
'cy',
'yi'];
var SCnewoptions = 
'<option value="af">Afrikaans</option>'+
'<option value="sq">Albanian</option>'+
'<option value="ar">Arabic</option>'+
'<option value="be">Belarusian</option>'+
'<option value="bg">Bulgarian</option>'+
'<option value="ca">Catalan</option>'+
'<option value="zh-TW">Chinese (traditional)</option>'+
'<option value="zh-CN">Chinese (simplified)</option>'+
'<option value="hr">Croatian</option>'+
'<option value="cs">Czech</option>'+
'<option value="da">Danish</option>'+
'<option value="nl">Dutch</option>'+
'<option value="en">English</option>'+
'<option value="et">Estonian</option>'+
'<option value="tl">Filipino</option>'+
'<option value="fi">Finnish</option>'+
'<option value="fr">French</option>'+
'<option value="gl">Galician</option>'+
'<option value="de">German</option>'+
'<option value="el">Greek</option>'+
'<option value="ht">Haitian creole</option>'+
'<option value="iw">Hebrew</option>'+
'<option value="hi">Hindi</option>'+
'<option value="hu">Hungarian</option>'+
'<option value="is">Icelandic</option>'+
'<option value="id">Indonesian</option>'+
'<option value="ga">Irish</option>'+
'<option value="it">Italian</option>'+
'<option value="ja">Japanese</option>'+
'<option value="lv">Latvian</option>'+
'<option value="lt">Lithuanian</option>'+
'<option value="mk">Macedonian</option>'+
'<option value="ms">Malay</option>'+
'<option value="mt">Maltese</option>'+
'<option value="no">Norwegian</option>'+
'<option value="fa">Persian</option>'+
'<option value="pl">Polish</option>'+
'<option value="pt">Portuguese</option>'+
'<option value="ro">Romanian</option>'+
'<option value="ru">Russian</option>'+
'<option value="sr">Serbian</option>'+
'<option value="sk">Slovak</option>'+
'<option value="sl">Slovenian</option>'+
'<option value="es">Spanish</option>'+
'<option value="sw">Swahili</option>'+
'<option value="sv">Swedish</option>'+
'<option value="th">Thai</option>'+
'<option value="tr">Turkish</option>'+
'<option value="uk">Ukrainian</option>'+
'<option value="vi">Vietnamese</option>'+
'<option value="cy">Welsh</option>'+
'<option value="yi">Yiddish</option>';
var SCTranslateableLanguages = [
'af',
'sq',
'ar',
'be',
'bg',
'ca',
'zh-CN',
'zh-TW',
'hr',
'cs',
'da',
'nl',
'en',
'et',
'tl',
'fi',
'fr',
'gl',
'de',
'el',
'ht',
'iw',
'hi',
'hu',
'is',
'id',
'ga',
'it',
'ja',
'lv',
'lt',
'mk',
'ms',
'mt',
'no',
'fa',
'pl',
'pt',
'ro',
'ru',
'sr',
'sk',
'sl',
'es',
'sw',
'sv',
'th',
'tr',
'uk',
'vi',
'cy',
'yi'];

